const SystemMessage = require('../models/SystemMessage');

// 获取当前用户的系统通知（分页）
exports.getSystemMessages = async (req, res) => {
  try {
    const userId = req.user._id;
    const page = parseInt(req.query.page) || 1;
    const pageSize = parseInt(req.query.pageSize) || 20;
    const total = await SystemMessage.countDocuments({ user: userId });
    const list = await SystemMessage.find({ user: userId })
      .sort({ createdAt: -1 })
      .skip((page - 1) * pageSize)
      .limit(pageSize);
    res.json({ total, list });
  } catch (err) {
    res.status(500).json({ message: '获取系统通知失败' });
  }
};

// 标记通知为已读
exports.markAsRead = async (req, res) => {
  try {
    const userId = req.user._id;
    const id = req.params.id;
    const msg = await SystemMessage.findOneAndUpdate(
      { _id: id, user: userId },
      { isRead: true },
      { new: true }
    );
    if (!msg) return res.status(404).json({ message: '通知不存在' });
    res.json({ message: '已标记为已读', data: msg });
  } catch (err) {
    res.status(500).json({ message: '标记已读失败' });
  }
};

// 新增通知（可在点赞/评论/关注等事件中调用）
exports.createSystemMessage = async (userId, type, content) => {
  try {
    await SystemMessage.create({ user: userId, type, content });
  } catch (err) {
    // 仅日志，不抛出
    console.error('创建系统通知失败', err);
  }
};
